package com.bee.member.controller;

import com.alibaba.fastjson.JSONObject;
import com.bee.base.BaseResponse;
import com.bee.constants.Constants;
import com.bee.member.feign.MemberLoginServiceFeign;
import com.bee.member.feign.WBAuthoriFeign;
import com.bee.member.input.dto.UserLoginInpDTO;
import com.bee.member.vo.LoginVo;
import com.bee.web.base.BaseWebController;
import com.bee.web.bean.MeiteBeanUtils;
import com.bee.web.constants.WebConstants;
import com.bee.web.utils.CookieUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import weibo4j.Account;
import weibo4j.Oauth;
import weibo4j.Users;
import weibo4j.http.AccessToken;
import weibo4j.model.User;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@Controller
public class WBAuthoriController extends BaseWebController {

    private static final String MB_WB_LOGIN = "member/wblogin";

    private static final String AUTHTYPE_CODE = "code";

    @Autowired
    private MemberLoginServiceFeign memberLoginServiceFeign;

    @Autowired
    private WBAuthoriFeign wbAuthoriFeign;

    /**
     * 重定向到首页
     */
    private static final String REDIRECT_INDEX = "redirect:/";

    /**
     * 生成QQ授权回调地址
     *
     * @return
     */
    @RequestMapping("/wbAuth")
    public String qqAuth(HttpServletRequest request) {
        try {
            //构建请求地址 如：https://api.weibo.com/oauth2/authorize?client_id=YOUR_CLIENT_ID&response_type=code&redirect_uri=http://a.com
            String authorizeURL = new Oauth().authorize(AUTHTYPE_CODE);
            return "redirect:" + authorizeURL;
        } catch (Exception e) {
            return ERROR_500_FTL;
        }
    }

    /**
     *
     * @param code
     * @return
     */
    @RequestMapping("/wbLogin")
    public String qqLoginBack(String code, HttpServletRequest request, HttpServletResponse response, HttpSession httpSession) {
        try {
            //根据code获取accessToken
            AccessToken accessTokenObj = new Oauth().getAccessTokenByCode(code);
            if (accessTokenObj == null) {
                return ERROR_500_FTL;
            }
            String accessToken = accessTokenObj.getAccessToken();
            if (StringUtils.isEmpty(accessToken)) {
                return ERROR_500_FTL;
            }
            // 使用accessToken获取用户openid
            String openUID = new Account(accessToken).getUid().getString("uid");

            if (StringUtils.isEmpty(openUID)) {
                return ERROR_500_FTL;
            }
            //查询该openId是否已经绑定了用户
            BaseResponse<JSONObject> findByOpenId = wbAuthoriFeign.findByOpenId(openUID);
            if (!isSuccess(findByOpenId)) {
                return ERROR_500_FTL;
            }
            Integer resultCode = findByOpenId.getCode();
            // 如果使用openid没有查询到用户信息，则跳转到绑定用户信息页面
            if (resultCode.equals(Constants.HTTP_RES_CODE_NOTUSER_203)) {
                // 使用openid获取用户信息
                Users um = new Users(accessToken);
                User user = um.showUserById(openUID);
                if (user == null) {
                    return ERROR_500_FTL;
                }
                String avatarURL100 = user.getAvatarLarge();
                // 返回用户头像页面展示
                httpSession.setAttribute("avatarURL100", avatarURL100);
                httpSession.setAttribute(WebConstants.LOGIN_WB_OPENID, openUID);
                return MB_WB_LOGIN;
            }
            // 自动实现登陆
            JSONObject data = findByOpenId.getData();
            String token = data.getString("token");
            CookieUtils.setCookie(request, response, WebConstants.LOGIN_TOKEN_COOKIENAME, token);
            return REDIRECT_INDEX;
        } catch (Exception e) {
            return ERROR_500_FTL;
        }
    }

    /**
     * openId信息与用户信息绑定
     *
     * @return
     */
    @RequestMapping("/wbJointLogin")
    public String wbJointLogin(@ModelAttribute("loginVo") LoginVo loginVo, Model model, HttpServletRequest request,
                               HttpServletResponse response, HttpSession httpSession) {

        // 1.获取用户openid
        String wbOpenId = (String) httpSession.getAttribute(WebConstants.LOGIN_WB_OPENID);
        if (StringUtils.isEmpty(wbOpenId)) {
            return ERROR_500_FTL;
        }

        // 2.将vo转换dto调用会员登陆接口
        UserLoginInpDTO userLoginInpDTO = MeiteBeanUtils.voToDto(loginVo, UserLoginInpDTO.class);
        userLoginInpDTO.setQqOpenId(wbOpenId);
        userLoginInpDTO.setLoginType(Constants.MEMBER_LOGIN_TYPE_PC);
        String info = webBrowserInfo(request);
        userLoginInpDTO.setDeviceInfor(info);
        BaseResponse<JSONObject> login = memberLoginServiceFeign.login(userLoginInpDTO);
        if (!isSuccess(login)) {
            setErrorMsg(model, login.getMsg());
            return MB_WB_LOGIN;
        }
        // 3.登陆成功之后如何处理 保持会话信息 将token存入到cookie 里面 首页读取cookietoken 查询用户信息返回到页面展示
        JSONObject data = login.getData();
        String token = data.getString("token");
        CookieUtils.setCookie(request, response, WebConstants.LOGIN_TOKEN_COOKIENAME, token);
        return REDIRECT_INDEX;
    }
}
